<template>
  <div class="employees-container">
    <div class="app-container">
      <PageTools>
        <!-- 插入到left插槽位置 -->
        <template #left>
          <span>本月: 社保在缴 公积金在缴</span>
        </template>
        <!-- 插入到right插槽位置 -->
        <template #right>
          <el-button type="warning" size="small" @click="channel">导入excel</el-button>
          <el-button v-allow="'import_employee'" type="danger" size="small" @click="educe">导出excel</el-button>
          <el-button type="primary" size="small" @click="dialogVisible=true">新增员工</el-button>
        </template>
      </PageTools>
      <el-table border :data="list" border:default-sort="{prop: 'workNumber'}">
        <el-table-column label="序号" type="index" />
        <el-table-column label="姓名" prop="username" />
        <el-table-column label="头像">
          <template slot-scope="scope">
            <Imgtou :src="scope.row.staffPhoto" />
          </template>
        </el-table-column>
        <el-table-column label="工号" prop="workNumber" />
        <el-table-column label="聘用形式" prop="formOfEmployment">
          <template slot-scope="scope">
            <!-- {{ scope.row.formOfEmployment }} -->
            类型:{{ formatEmployment(scope.row.formOfEmployment) }}
          </template>
        </el-table-column>
        <el-table-column label="部门" prop="departmentName" />
        <el-table-column label="入职时间" prop="timeOfEntry" sortable />
        <el-table-column label="操作" width="280">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="$router.push('/employees/detail/'+scope.row.id)">查看</el-button>
            <el-button type="text" size="small" @click="fenRole(scope.row)">分配角色</el-button>
            <el-button type="text" size="small" @click="delStaffApi(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div style="height: 60px; margin-top: 10px">
        <!-- 分页 -->
        <el-pagination
          layout="total, sizes,prev, pager, next, jumper"
          :total="total"
          :current-page="pageParams.page"
          :page-size="pageParams.size"
          :page-sizes="[2,5,10]"
          @current-change="hCurrentChange"
          @size-change="hSizeChange"
        />
      </div>
    </div>
    <el-dialog
      title="添加"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      width="50%"
    >
      <hDialog
        v-if="dialogVisible"
        @close="dialogVisible = false"
        @update-empolyee="hUpdateEmpolyee"
      />
    </el-dialog>
    <!-- 角色权限分配 -->
    <el-dialog
      title="角色权限分配"
      :visible.sync="dialogVisibleRole"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      width="50%"
    >
      <assignRole
        v-if="dialogVisibleRole"
        :cur-employe-id="curEmployeId"
        @close="dialogVisibleRole = false"
      />
    </el-dialog>
  </div>
</template>
<script>
import assignRole from './components/assignRole.vue'
import hDialog from './employessDialog.vue'
// 局部注册 导入
// import PageTools from '@/components/PageTools'
import { getEmployeeList, delStaff } from '@/api/employees'
import employees from '@/constant/employees'
// 将employees.hireType数据进行处理 优化细节
const hireType = employees.hireType.reduce((obj, it) => {
  obj[it.id] = it.value
  return obj
}, {})
export default {
  name: 'Employees',
  components: {
    // 局部注册
    // PageTools
    hDialog,
    assignRole
  },
  data() {
    return {
      list: [],
      // 分页数据
      total: 0,
      pageParams: {
        page: 1, // 当前页码
        size: 5 // 每页几条
      },
      // 弹出框
      dialogVisible: false,
      dialogVisibleRole: false,
      curEmployeId: ''
    }
  },
  created() {
    this.loadEmployeeList()
  },
  methods: {
    // 获取表格数据
    async loadEmployeeList() {
      try {
        const res = await getEmployeeList(this.pageParams)
        this.list = res.data.rows
        this.total = res.data.total
        console.log(this.list)
        this.list.forEach(item => {
          // item.timeOfEntry = item.timeOfEntry.split('T').shift()
          item.timeOfEntry = item.timeOfEntry.replace('T16:00:00.000Z', '')
        })
      } catch (err) {
        console.log(err)
        this.$message.error('加载员工数据失败')
      }
    },
    // 定义聘用形式方法 '正式' : '非正式'
    formatEmployment(num) {
      return hireType[num]
    },
    // 会自动接收当前点击的页码
    hCurrentChange(curPage) {
      // alert(curPage)
      // 1. 更新页码
      this.pageParams.page = curPage
      // 2. 重发请求
      this.loadEmployeeList()
    },
    // 每页几条
    hSizeChange(curSize) {
      console.log(curSize)
      // 1. 更新每页的条数
      this.pageParams.size = curSize
      // 2. 重发请求
      this.loadEmployeeList()
    },
    // 删除员工
    delStaffApi(id) {
      if (this.list.length === 1) {
        this.pageParams.page--
        if (this.pageParams.page < 1) {
          this.pageParams.page = 1
        }
      }
      console.log(id)
      this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        console.log(11111)
        // 删除数据
        await delStaff(id)
        // 重新渲染
        await this.loadEmployeeList()
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '删除失败'
        })
      })
    },
    hUpdateEmpolyee() {
      this.dialogVisible = false
      // 跳转页面到最后一页
      this.total++
      this.pageParams.page = Math.ceil(this.total / this.pageParams.size)
      this.loadEmployeeList()
    },
    // excel 导入
    channel() {
      this.$router.push('/import')
    },
    // excel导出
    educe() {
      import('@/vendor/Export2Excel').then(async excel => {
        // 发ajax请求，获取数据
        const res = await getEmployeeList(this.pageParams)
        const list = res.data.rows
        console.log('从后端获取的数据', list)

        const { header, data } = this.formatData(list)
        // excel表示导入的模块对象
        console.log(header, data)
        excel.export_json_to_excel({
          // header: ['姓名', '工资'], // 表头 必填
          header: header, // 表头 必填
          data: data,
          // data: [
          //   ['刘备11111111111111', 100],
          //   ['关羽', 500]
          // ], // 具体数据 必填
          filename: 'excel-list', // 文件名称
          autoWidth: true, // 宽度是否自适应
          bookType: 'xlsx' // 生成的文件类型
        })
      })
    },
    // 处理excel导出数据
    formatData(list) {
      const map = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }
      console.log(list)
      let header = []
      // header = ['id', 'mobile', 'username', .....]
      // data = [
      //     ['65c2', '1380000002', '管理员', ....],
      //     ['65c3', '1380000003', '孙财', ....],
      // ]
      let data = []
      // 开始代码
      // 找到一个元素
      const one = list[0]
      if (!one) {
        return { header, data }
      }
      header = Object.keys(one).map(key => {
        return map[key]
      })

      // data把list中每一个对象转成 对应的value数组
      data = list.map(obj => {
        // 把  Obj['formOfEmployment']: 1 , 2   ---> '正式'， '非正式'
        const key = obj['formOfEmployment'] // 1, 2
        obj['formOfEmployment'] = employees.hireType[key]['value'] // hireTypEnmu:{1:'正式', '2':'非正式' }
        console.log(obj['formOfEmployment'])
        return Object.values(obj)
      })

      return { header, data }
    },
    // 分配角色
    fenRole({ id }) {
      this.dialogVisibleRole = true
      this.curEmployeId = id
    }
  }
}
</script>
